import moment from 'moment'
/**
 * Created by PanJiaChen on 16/11/18.
 */

/**
 * Parse the time to string
 * @param {(Object|string|number)} time
 * @param {string} cFormat
 * @returns {string | null}
 */
export function parseTime(time, cFormat) {
  if (arguments.length === 0 || !time) {
    return null
  }
  const format = cFormat || '{y}-{m}-{d} {h}:{i}:{s}'
  let date
  if (typeof time === 'object') {
    date = time
  } else {
    if ((typeof time === 'string')) {
      if ((/^[0-9]+$/.test(time))) {
        // support "1548221490638"
        time = parseInt(time)
      } else {
        // support safari
        // https://stackoverflow.com/questions/4310953/invalid-date-in-safari
        time = time.replace(new RegExp(/-/gm), '/')
      }
    }

    if ((typeof time === 'number') && (time.toString().length === 10)) {
      time = time * 1000
    }
    date = new Date(time)
  }
  const formatObj = {
    y: date.getFullYear(),
    m: date.getMonth() + 1,
    d: date.getDate(),
    h: date.getHours(),
    i: date.getMinutes(),
    s: date.getSeconds(),
    a: date.getDay()
  }
  const time_str = format.replace(/{([ymdhisa])+}/g, (result, key) => {
    const value = formatObj[key]
    // Note: getDay() returns 0 on Sunday
    if (key === 'a') {
      return ['日', '一', '二', '三', '四', '五', '六'][value]
    }
    return value.toString().padStart(2, '0')
  })
  return time_str
}

/**
 * @param {number} time
 * @param {string} option
 * @returns {string}
 */
export function formatTime(time, option) {
  if (('' + time).length === 10) {
    time = parseInt(time) * 1000
  } else {
    time = +time
  }
  const d = new Date(time)
  const now = Date.now()

  const diff = (now - d) / 1000

  if (diff < 30) {
    return '刚刚'
  } else if (diff < 3600) {
    // less 1 hour
    return Math.ceil(diff / 60) + '分钟前'
  } else if (diff < 3600 * 24) {
    return Math.ceil(diff / 3600) + '小时前'
  } else if (diff < 3600 * 24 * 2) {
    return '1天前'
  }
  if (option) {
    return parseTime(time, option)
  } else {
    return (
      d.getMonth() +
      1 +
      '月' +
      d.getDate() +
      '日' +
      d.getHours() +
      '时' +
      d.getMinutes() +
      '分'
    )
  }
}

/**
 * @param {string} url
 * @returns {Object}
 */
export function param2Obj(url) {
  const search = decodeURIComponent(url.split('?')[1]).replace(/\+/g, ' ')
  if (!search) {
    return {}
  }
  const obj = {}
  const searchArr = search.split('&')
  searchArr.forEach(v => {
    const index = v.indexOf('=')
    if (index !== -1) {
      const name = v.substring(0, index)
      const val = v.substring(index + 1, v.length)
      obj[name] = val
    }
  })
  return obj
}

/**
 *
 * @param {Array} listItem
 * @param {Object} value
 */
export function addNoneListItem(listItem, value) {
  if (listItem) {
    listItem.splice(0, 0, {
      label: '请选择',
      value: value
    })
  }
  return listItem
}

/**
 *
 */
export function getA_ZArray() {
  const array = []
  for (let i = 0; i < 26; i++) {
    const c = String.fromCharCode((65 + i))
    array.push({
      value: c,
      label: c
    })
  }
  for (let i = 0; i < 9; i++) {
    array.push({
      value: i,
      label: i
    })
  }
  return array
}

export function get0_9Array() {
  const array = []
  for (let i = 0; i < 9; i++) {
    array.push({
      value: i,
      label: i
    })
  }
  return array
}
export function formatDate(data) {
  var date = data
  var y = date.getFullYear()
  var m = date.getMonth() + 1
  m = m < 10 ? '0' + m : m
  var d = date.getDate()
  d = d < 10 ? '0' + d : d
  return y + '-' + m + '-' + d
}

export function formatDateBatchCode(data) {
  var date = data
  var y = date.getFullYear()
  var m = date.getMonth() + 1
  m = m < 10 ? '0' + m : m
  var d = date.getDate()
  d = d < 10 ? '0' + d : d
  return y + m + d
}
// 时间转换
export function formatDateTime(data) {
  var date = data
  var y = date.getFullYear()
  var m = date.getMonth() + 1
  m = m < 10 ? '0' + m : m
  var d = date.getDate()
  d = d < 10 ? '0' + d : d
  var h = date.getHours()
  h = h < 10 ? '0' + h : h
  var minute = date.getMinutes()
  var second = date.getSeconds()
  minute = minute < 10 ? '0' + minute : minute
  second = second < 10 ? '0' + second : second
  return y + '-' + m + '-' + d + ' ' + h + ':' + minute + ':' + second
}

export function getBeginDay(delta) {
  const time = new Date()
  time.setDate(time.getDate() + delta)
  time.setHours(0)
  time.setMinutes(0)
  time.setSeconds(0)
  time.setMilliseconds(0)
  return time
}

export function getEndDay(delta, flag) {
  // const time = new Date(new Date().toLocaleDateString())
  const time = new Date()
  time.setDate(time.getDate() + delta)
  time.setHours(23)
  time.setMinutes(59)
  time.setSeconds(59)
  time.setMilliseconds(999)
  return time
}

export function getBeginWeek(delta) {
  const time = new Date()
  time.setDate(time.getDate() + (delta * 7) - time.getDay() + 1)
  time.setHours(0)
  time.setMinutes(0)
  time.setSeconds(0)
  time.setMilliseconds(0)
  return time
}

export function getEndWeek(delta) {
  const time = new Date()
  time.setDate(time.getDate() + ((delta + 1) * 7) - time.getDay())
  time.setHours(23)
  time.setMinutes(59)
  time.setSeconds(59)
  time.setMilliseconds(999)
  return time
}

export function getBeginMonth(delta) {
  const time = new Date()
  time.setFullYear(time.getFullYear())
  time.setMonth(time.getMonth() + delta)
  time.setDate(1)
  time.setHours(0)
  time.setMinutes(0)
  time.setSeconds(0)
  time.setMilliseconds(0)
  return time
}

export function getEndMonth(delta) {
  const time = new Date()
  time.setFullYear(time.getFullYear())
  time.setMonth(time.getMonth() + delta + 1)
  time.setDate(1)
  time.setDate(time.getDate() - 1)
  time.setHours(23)
  time.setMinutes(59)
  time.setSeconds(59)
  time.setMilliseconds(999)
  return time
}

export function getBeginYear(delta) {
  const time = new Date()
  time.setFullYear(time.getFullYear() + delta)
  time.setMonth(1)
  time.setDate(1)
  time.setHours(0)
  time.setMinutes(0)
  time.setSeconds(0)
  time.setMilliseconds(0)
  return time
}

export function getEndYear(delta) {
  const time = new Date()
  time.setFullYear(time.getFullYear() + delta + 1)
  time.setMonth(1)
  time.setDate(1)
  time.setDate(time.getDate() - 1)
  time.setHours(23)
  time.setMinutes(59)
  time.setSeconds(59)
  time.setMilliseconds(999)
  return time
}

export function getThreeMonth(delta) {
  const time = new Date()
  time.setFullYear(time.getFullYear())
  time.setMonth(time.getMonth() - delta + 1)
  return time
}

export function getOneYear(delta) {
  const time = new Date()
  time.setFullYear(time.getFullYear() - delta)
  return time
}
export function getMonth(value) {
  let time
  if (value instanceof Date) {
    time = value
  } else if (value instanceof String) {
    time = new Date(value)
  } else {
    console.error('错误的时间格式：', value)
    return [null, null]
  }
  const start = new Date(time.getFullYear(), time.getMonth(), 1, 0, 0, 0, 0)
  const end = new Date(time.getFullYear(), time.getMonth() + 1, 1, 0, 0, 0, -1)
  return [start, end]
}

export function getTimePickerShortcuts() {
  return [{
    text: '今天',
    onClick(picker) {
      picker.$emit('pick', [getBeginDay(0), getEndDay(0)])
    }
  }, {
    text: '昨天',
    onClick(picker) {
      picker.$emit('pick', [getBeginDay(-1), getEndDay(-1)])
    }
  }, {
    text: '本周',
    onClick(picker) {
      picker.$emit('pick', [getBeginWeek(0), getEndDay(0)])
    }
  }, {
    text: '上周',
    onClick(picker) {
      picker.$emit('pick', [getBeginWeek(-1), getEndWeek(-1)])
    }
  }, {
    text: '本月',
    onClick(picker) {
      picker.$emit('pick', [getBeginMonth(0), getEndDay(0)])
    }
  }, {
    text: '上月',
    onClick(picker) {
      picker.$emit('pick', [getBeginMonth(-1), getEndMonth(-1)])
    }
  }]
}
export function getTimePickerShortcuts2() {
  return [
    {
      text: '一周',
      onClick(picker) {
        const date = new Date()
        date.setTime(date.getTime() + 3600 * 1000 * 24 * 7)
        picker.$emit('pick', date)
      }
    },
    {
      text: '一月',
      onClick(picker) {
        const date = new Date()
        date.setTime(date.getTime() + 3600 * 1000 * 24 * 30)
        picker.$emit('pick', date)
      }
    },
    {
      text: '一年',
      onClick(picker) {
        const date = new Date()
        date.setTime(date.getTime() + 3600 * 1000 * 24 * 365)
        picker.$emit('pick', date)
      }
    },
    {
      text: '两年',
      onClick(picker) {
        const date = new Date()
        date.setTime(date.getTime() + 3600 * 1000 * 24 * 365 * 2)
        picker.$emit('pick', date)
      }
    }
  ]
}

export function getDatePickerShortcuts(options) {
  const shortcuts = []
  const array = options || []
  array.forEach(e => {
    if (e === 'd0') {
      shortcuts.push({
        text: '今天',
        onClick(picker) {
          picker.$emit('pick', [getBeginDay(0), getEndDay(0)])
        }
      })
    } else if (e === 'd-1') {
      shortcuts.push({
        text: '昨天',
        onClick(picker) {
          picker.$emit('pick', [getBeginDay(-1), getEndDay(-1)])
        }
      })
    } else if (e === 'w0') {
      shortcuts.push({
        text: '本周',
        onClick(picker) {
          picker.$emit('pick', [getBeginWeek(0), getEndDay(0)])
        }
      })
    } else if (e === 'w-1') {
      shortcuts.push({
        text: '上周',
        onClick(picker) {
          picker.$emit('pick', [getBeginWeek(-1), getEndWeek(-1)])
        }
      })
    } else if (e === 'm0') {
      shortcuts.push({
        text: '本月',
        onClick(picker) {
          picker.$emit('pick', [getBeginMonth(0), getEndDay(0)])
        }
      })
    } else if (e === 'm-1') {
      shortcuts.push({
        text: '上月',
        onClick(picker) {
          picker.$emit('pick', [getBeginMonth(-1), getEndMonth(-1)])
        }
      })
    } else if (e === 'y0') {
      shortcuts.push({
        text: '本年',
        onClick(picker) {
          picker.$emit('pick', [getBeginYear(0), getEndDay(0)])
        }
      })
    } else if (e === 'y-1') {
      shortcuts.push({
        text: '去年',
        onClick(picker) {
          picker.$emit('pick', [getBeginYear(-1), getEndYear(-1)])
        }
      })
    } else if (e === '-3') {
      shortcuts.push({
        text: '近三天',
        onClick(picker) {
          picker.$emit('pick', [getBeginDay(-3), getEndDay(0)])
        }
      })
    } else if (e === '-7') {
      shortcuts.push({
        text: '近一周',
        onClick(picker) {
          picker.$emit('pick', [getBeginDay(-7), getEndDay(0)])
        }
      })
    } else if (e === '-30') {
      shortcuts.push({
        text: '近一月',
        onClick(picker) {
          picker.$emit('pick', [getBeginDay(-30), getEndDay(0)])
        }
      })
    } else if (e === '-90') {
      shortcuts.push({
        text: '近三月',
        onClick(picker) {
          picker.$emit('pick', [getBeginDay(-90), getEndDay(0)])
        }
      })
    } else if (e === '-365') {
      shortcuts.push({
        text: '近一年',
        onClick(picker) {
          picker.$emit('pick', [getBeginDay(-365), getEndDay(0)])
        }
      })
    } else {
      try {
        const number = parseInt(e)
        shortcuts.push({
          text: '近' + Math.abs(e) + '天',
          onClick(picker) {
            picker.$emit('pick', [getBeginDay(number), getEndDay(0)])
          }
        })
      } catch {
        //
      }
    }
  })
  return shortcuts
}

export function getTimeShortcuts() {
  return [
    {
      value: '待进行',
      type: 'primary',
      id: 1
    },
    {
      value: '本月',
      timeEnd: moment(getEndDay(0)).format('YYYY-MM-DD HH:mm:ss'),
      timeBegin: moment(getBeginMonth(0)).format('YYYY-MM-DD HH:mm:ss'),
      type: '',
      id: 2
    },
    {
      value: '近三月',
      timeEnd: moment(getEndDay(0)).format('YYYY-MM-DD HH:mm:ss'),
      timeBegin: moment(getThreeMonth(3)).format('YYYY-MM-DD HH:mm:ss'),
      type: '',
      id: 3
    },
    {
      value: '近一年',
      timeEnd: moment(getEndDay(0)).format('YYYY-MM-DD HH:mm:ss'),
      timeBegin: moment(getOneYear(1)).format('YYYY-MM-DD HH:mm:ss'),
      type: '',
      id: 4
    }
  ]
}
export function getNowDate() {
  const date = new Date()
    .toLocaleDateString()
    .split('/')
    .map((item) => {
      if (item < 10) {
        return '0' + item
      } else {
        return item
      }
    })
    .join('-')
  return date
}

export function isDatePassby(date) {
  if (date) {
    const currentDate = moment(new Date()).format('YYYY-MM-DD')
    return currentDate > date
  }
  return false
}

export function formatByKeyValue(options, key) {
  options = options || []
  let label = ''
  options.forEach((e) => {
    if (e.key == key) {
      label = e.value
    }
  })
  return label
}

export function isTagType(status) {
  return status === 1 ? 'success' : status === 2 ? 'danger' : 'info'
}
